package com.yuedou.jylt;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.proxy.IUpdateProxy;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateChecker;
import com.yuedou.jylt.activity.EstateInfoActivity;
import com.yuedou.jylt.activity.VisitorActivity;
import com.yuedou.jylt.constant.Const;
import com.yuedou.jylt.manager.DifferentDisplay;
import com.yuedou.jylt.utils.DateUtil;
import com.yuedou.jylt.utils.StatusBarUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.text_date)
    TextView txtDate;
    @BindView(R.id.text_date_time)
    TextView txtDateTime;
//    @BindView(R.id.text_device_serial)
//    TextView textDeviceSerial;


    public static final String TAG = "MainActivity";
    private Unbinder unbinder;

    private Context context;

    private DifferentDisplay mPresentation;
    private DisplayManager mDisplayManager;// 屏幕管理类
    /**
     *  init 方法
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);
        StatusBarUtils.setWindowStatusBarColor(this);

        unbinder = ButterKnife.bind(this);

        context = MainActivity.this;

        ApplicationInfo applicationInfo = getApplicationInfo();
        Log.i(TAG, "onCreate: " + applicationInfo.nativeLibraryDir);

        txtDate.setText(DateUtil.getNowDay(new Date()) + "  " + DateUtil.getWeekOfDate(new Date()));
        txtDateTime.setText(DateUtil.getNowHourMinTime(new Date()));

//        deviceId = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_SERIAL_NUM);
//        textDeviceSerial.setText(deviceId);
        updateApp();
        //时间
        startThread();
        if (Build.VERSION.SDK_INT >= 23) {
            if (mPresentation == null) {
                //下方屏
                mDisplayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
                Display[] displays = mDisplayManager.getDisplays();
                if(displays.length > 1){
                    mPresentation = new DifferentDisplay(context, displays[displays.length - 1]);// displays[1]是副屏
                    mPresentation.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    mPresentation.show();
                }

            }
        }
//        showDisplay();
    }

    private void showDisplay() {
//        DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
//        Display[] presentationDisplays = displayManager.getDisplays(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//        if (presentationDisplays.length > 0) {
//            //判断是否有双屏
//            // displays[0] 主屏
//            // displays[1] 副屏
//            Display display = presentationDisplays[1];
//
//            if (mPresentation == null) {
//                mPresentation = new DifferentDisplay(this, display);
//                try {
//                    mPresentation.show();
//                } catch (WindowManager.InvalidDisplayException e) {
//                    mPresentation = null;
//                }
//            }
//        }

        //双屏显示
        DisplayManager mDisplayManager;//屏幕管理类
        Display[] displays;//屏幕数组
        mDisplayManager =(DisplayManager)MainActivity.this.getSystemService(Context.DISPLAY_SERVICE);
        displays =mDisplayManager.getDisplays(); //得到显示器数组
        mPresentation =new DifferentDisplay
                (getApplicationContext(),displays[1]);//displays[1]是副屏
        mPresentation.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        mPresentation.show();
    }



    //开启一个子线程
    private void startThread(){
        new Thread(){
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(1000);
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }while (true);
            }
        }.start();
    }

    //在主线程中进行数据处理
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    String time = DateUtil.getNowHourMinTime(new Date());
                    txtDateTime.setText(time);
                    break;
            }
        }
    };


    /**
     * 检查能否找到动态链接库，如果找不到，请修改工程配置
     *
     * @param libraries 需要的动态链接库
     * @return 动态库是否存在
     */
    private boolean checkSoFile(String[] libraries) {
        File dir = new File(getApplicationInfo().nativeLibraryDir);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return false;
        }
        List<String> libraryNameList = new ArrayList<>();
        for (File file : files) {
            libraryNameList.add(file.getName());
        }
        boolean exists = true;
        for (String library : libraries) {
            exists &= libraryNameList.contains(library);
        }
        return exists;
    }

    /**
     *  版本号检测
     */
    public void updateApp(){
        XUpdate.newBuild(context)
                .updateUrl(Const.APP_VERSION_URL)
                .updateChecker(new DefaultUpdateChecker() {
                    @Override
                    public void onBeforeCheck() {
                        super.onBeforeCheck();
                    }

                    @Override
                    public void onAfterCheck() {
                        super.onAfterCheck();
                    }

                    @Override
                    public void processCheckResult(@NonNull String result, @NonNull IUpdateProxy updateProxy) {
                        super.processCheckResult(result, updateProxy);
                        try {
                            UpdateEntity updateEntity = updateProxy.parseJson(result);
                            if (updateEntity.isHasUpdate()) {
                                Log.d("TAG", "processCheckResult: 111");
                            } else {
                                Log.d("TAG", "processCheckResult: 222");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .update();
    }

    /**
     *  初始化按钮操作
     */
    @OnClick({R.id.btn_clinker_face,R.id.btn_clinker_wynotice,R.id.btn_clinker_camera,
            R.id.btn_clinker_shopping,
            R.id.btn_clinker_estate_info,R.id.btn_clinker_active, R.id.btn_exit})
    public void onClick(View view) {
        System.out.println("onClick:" + view.getId());
        switch (view.getId()) {

            //访客通行
            case R.id.btn_clinker_face:
                Intent intent = new Intent(context, VisitorActivity.class);
                startActivity(intent);
                break;
            //物业公告
            case R.id.btn_clinker_wynotice:
//                Intent intent1 = new Intent(context, GongGaoActivity.class);
//                startActivity(intent1);
                Toast.makeText(this,"功能未开启",Toast.LENGTH_LONG).show();
                break;
                //小区介绍
            case R.id.btn_clinker_estate_info:
                Intent intent2 = new Intent(context, EstateInfoActivity.class);
                startActivity(intent2);
                break;
                //业主活动
            case R.id.btn_clinker_active:
//                Intent intent3 = new Intent(context, EstateActionActivity.class);
//                startActivity(intent3);
                Toast.makeText(this,"功能未开启",Toast.LENGTH_LONG).show();
                break;
            //监控查询
            case R.id.btn_clinker_camera:
//                Intent intent4 = new Intent(context, EstateActionActivity.class);
//                startActivity(intent4);
                Toast.makeText(this,"功能未开启",Toast.LENGTH_LONG).show();
                break;
            //购物团购
            case R.id.btn_clinker_shopping:
//                Intent intent5 = new Intent(context, EstateActionActivity.class);
//                startActivity(intent5);
                Toast.makeText(this,"功能未开启",Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_exit:
                android.os.Process.killProcess(android.os.Process.myPid()); //获取PID 
                finish();
                System.exit(0); //常规java、c#的标准退出法，返回值为0代表正常退出
                break;
        }
    }

    /* 禁用返回键
     *(non-Javadoc)
     * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}